let effects = new Map();

let currentEffect = null;

export function effect(fn) {
    currentEffect = fn;
    fn();
    currentEffect = null;
}

export function reactive(object) {
    const proxy = new Proxy(object, {
        set(obj, prop, value) {
            obj[prop] = value;

            effects.get(obj)?.get(prop)?.forEach(eff => eff());
            return true;
        },
        get(obj, prop) {
            if (currentEffect) {
                if (!effects.has(obj)) {
                    effects.set(obj, new Map());
                }
                if (!effects.get(obj).has(prop)) {
                    effects.get(obj).set(prop, []);
                }
                effects.get(obj)?.get(prop).push(currentEffect);
            }
            return obj[prop];
        }
    })
    return proxy;
}
